<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use Exception;
use fast\Random;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 区域经销商账号管理
 *
 * @icon fa fa-circle-o
 */
class Regionserviceuser extends Backend
{

    /**
     * Regionserviceuser模型对象
     * @var \app\common\model\Regionserviceuser
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Regionserviceuser;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 验证
     * */
    protected function check($params,$id=0){
        if(!empty($id)){
            $data=[
                ['name', 'require', '员工姓名不能为空'],
                ['password', 'regex:\S{6,30}', '密码长度必须在6-30位之间，不能包含空格'],
                ['mobile', 'require|regex:/^1\d{10}$/|unique:regionserviceuser,mobile,'.$id, '手机号码（账号）不能为空|手机号码（账号）格式错误|手机号码（账号）已存在'],
            ];
        }else{
            $data=[
                ['name', 'require', '员工姓名不能为空'],
                //['username', 'require|regex:\w{3,30}|unique:regionserviceuser,username', '账号不能为空|账号只能由3-30位数字、字母、下划线组合|账号已存在'],
                ['password', 'require|regex:\S{6,30}', '密码不能为空|密码长度必须在6-30位之间，不能包含空格'],
                ['mobile', 'require|regex:/^1\d{10}$/|unique:regionserviceuser,mobile', '手机号码（账号）不能为空|手机号码（账号）格式错误|手机号码（账号）已存在'],
            ];
        }
        $validate = new \think\Validate($data);
        if (!$validate->check($params)) {
            $this->error('提交失败：' . $validate->getError());
        }
        return true;
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = $this->request->request('filter');
            $filter=(array)json_decode($filter, true);
            $regionservice_id=0;
            if(isset($filter["regionservice_id"])){
                $regionservice_id=$filter["regionservice_id"];
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['regionservice'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('regionservice')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items(),"regionservice_id"=>$regionservice_id);

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        $regionservice_id=!$this->request->param("regionservice_id")?0:$this->request->param("regionservice_id");
        if (false === $this->request->isPost()) {
            $regionservice=\app\common\model\Regionservice::field("name")->where(["id"=>$regionservice_id])->find();
            $this->assign("regionservice_id",$regionservice_id);
            $this->assign("regionservice_name",$regionservice["name"]??'');
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        $res=$this->check($params);
        if(!$res) return $res;
        Db::startTrans();
        try {
            $params['salt'] = Random::alnum();
            $params['password'] = md5(md5($params['password']) . $params['salt']);
            $params["regionservice_id"]=$params["regionservice_id"]??$regionservice_id;
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $regionservice_id=!$this->request->param("regionservice_id")?0:$this->request->param("regionservice_id");
        if (false === $this->request->isPost()) {
            $regionservice=\app\common\model\Regionservice::field("name")->where(["id"=>$regionservice_id])->find();
            $this->assign("regionservice_id",$regionservice_id);
            $this->assign("regionservice_name",$regionservice["name"]??'');
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        $res=$this->check($params,$ids);
        if(!$res) return $res;
        Db::startTrans();
        try {
            if ($params['password']) {
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
            } else {
                unset($params['password'], $params['salt']);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
}
